package cn.tedu.csmall.server.service.impl;

import cn.tedu.csmall.server.exception.ServiceException;
import cn.tedu.csmall.server.mapper.BrandMapper;
import cn.tedu.csmall.server.pojo.dto.BrandAddNewDTO;
import cn.tedu.csmall.server.pojo.entity.Brand;
import cn.tedu.csmall.server.pojo.vo.BrandDetailVO;
import cn.tedu.csmall.server.pojo.vo.BrandListItemVO;
import cn.tedu.csmall.server.repo.IBrandRepository;
import cn.tedu.csmall.server.repo.impl.BrandRepositoryImpl;
import cn.tedu.csmall.server.service.IBrandService;
import cn.tedu.csmall.server.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lixin
 * @Date 2022/8/26
 */
@Service
@Slf4j
public class BrandService implements IBrandService {

    public BrandService() {
        System.out.println("BrandService.BrandService");
    }

    @Autowired
    IBrandRepository brandRepository;

    @Autowired
    private BrandMapper mapper;

    @Override
    public void addNew(BrandAddNewDTO brandAddNewDTO) {
        //查询品牌是否存在
        //select count(*) from pms_brand where name=?

        String name = brandAddNewDTO.getName();
        final int count = mapper.countByName(name);
        if (count > 0) {
            String message = "添加失败，已有该品牌";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        //创建实体对象（Mapper的方法参数是实体类型）
        Brand brand = new Brand();
        //将参数值复制到brand 实体对象中
        BeanUtils.copyProperties(brandAddNewDTO, brand);
        //补全数据
        brand.setSales(0);
        brand.setPositiveCommentCount(0);
        brand.setCommentCount(0);
        brand.setProductCount(0);
        brand.setEnable(1);
        int rows = mapper.insert(brand);
        if (rows != 1) {
            String message = "添加失败，服务器忙！请稍后重试";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public List<BrandListItemVO> list() {
        List<BrandListItemVO> list = brandRepository.getList();
//        if (!list.isEmpty()) {
//            return list;
//        }
//        List<BrandListItemVO> sqlList = mapper.list();
//        if (!sqlList.isEmpty()) {
//            brandRepository.putList(sqlList);
//        }
        return list;
    }

    @Override
    public void deleteById(Long id) {
        final BrandDetailVO brand = mapper.getById(id);
        if (brand == null) {
            throw new ServiceException(ServiceCode.ERR_DELETE, "数据异常，没有该条数据,id=" + id);
        }
        final int row = mapper.deleteById(id);
        if (row != 1) {
            throw new ServiceException(ServiceCode.ERR_UNKNOWN, "服务器繁忙,删除失败id=" + id);
        }
    }
}
